﻿
using Newtonsoft.Json;
using System.Net;

namespace HelloWorld.Utils
{
    // 自定义响应中间件
    public class ApiResponseMiddleware
    {
        private readonly RequestDelegate _next;

        public ApiResponseMiddleware(RequestDelegate next) {  _next = next; }  // 代表下一个中间件

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private static Task HandleExceptionAsync(HttpContext context, Exception exception)  // 包含所有请求信息
        {
            var code = HttpStatusCode.BadRequest;

            //if (exception is SomeException) code = HttpStatusCode.BadRequest;
            var result = JsonConvert.SerializeObject(new ApiResponse((int)code, null, exception.Message));
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = 200;  // 错误响应也是200
            return context.Response.WriteAsync(result);
        }
    }
}
